package com.rm.system.index;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.interfaces.RSAPublicKey;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.demo.blog.Blog;
import com.jfinal.core.Controller;
import com.rm.system.Constants;
import com.rm.system.UrlConfig;
import com.rm.system.model.Log;
import com.rm.system.model.User;
import com.rm.system.util.RSA;

/**
 * IndexController
 */
public class IndexController extends Controller {
	Logger log = Logger.getLogger(getClass());
	private int w = 70;
	private int h = 26;
	public static final String VALIDATE_CODE = "validateCode";
	private static final String LOGIN_ERROR_NUM = "loginErrorNum";

	/**
	 * 首页
	 */
	public void index() {
		render("index.html");
	}

	/**
	 * 条状登陆页面
	 */
	public void jump() {
		render("jump.html");
	}

	public void validateCode() {
		try {
			createImage(getRequest(), getResponse());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderNull();
	}

	/**
	 * 显示登陆页面。
	 */
	public void loginView() {
		// 生成公匙
		RSAPublicKey publicKey = RSA.getDefaultPublicKey();
		// 系数
		String modulus = new String(Hex.encodeHex(publicKey.getModulus()
				.toByteArray()));
		// 样品、典型、指数
		String exponent = new String(Hex.encodeHex(publicKey
				.getPublicExponent().toByteArray()));

		// 判断是否要验证码
		Boolean hasValidateCode = false;
		Object numObj = getSessionAttr(LOGIN_ERROR_NUM);
		if (numObj != null && (Integer) numObj >= 3) {
			hasValidateCode = true;
		}

		setAttr("hasValidateCode", hasValidateCode.toString());
		setAttr("modulus", modulus);
		setAttr("exponent", exponent);
		setAttr("msg", getAttr("msg"));
		render(UrlConfig.VIEW_COMMON_LOGIN);
	}

	public void login() {
		// String username = getPara("username");
		// String password = getPara("password");
		// 校验码
		try {
			String valideCode = getPara("validateCode");
			Boolean rememberMe = getParaToBoolean("rememberMe");
			String sessionValidateCode = getSessionAttr(VALIDATE_CODE);
			if (StringUtils.isNotEmpty(valideCode)
					&& !valideCode.toUpperCase().equals(sessionValidateCode)) {
				//
				forwardAction("验证码不正确", UrlConfig.LOGIN);
				return;
			}

			String[] result = RSA.decryptUsernameAndPwd(getPara("key"));
			String username = result[0];
			String password = result[1];// Sec.md5(result[1]);

			UsernamePasswordToken token = new UsernamePasswordToken(username,
					password);
			Subject subject = SecurityUtils.getSubject();
			if (!subject.isAuthenticated()) {
				token.setRememberMe(rememberMe==null?false:rememberMe);
				subject.login(token);
				subject.getSession(true).setAttribute(Constants.SESSION_USER,
						User.dao.findByName(username));
			}
			// 记录登录日志
			Log.dao.insert(this, Log.EVENT_LOGIN);

			setSessionAttr(LOGIN_ERROR_NUM, 0);
			redirect("/");

		} catch (UnknownAccountException e) {
			forwardAction("用户名不存在", UrlConfig.LOGIN);
			setLoginErrorNumber();
		} catch (IncorrectCredentialsException e) {
			forwardAction("密码错误", UrlConfig.LOGIN);
			setLoginErrorNumber();
		} catch (LockedAccountException e) {
			setLoginErrorNumber();
			forwardAction("对不起 帐号被封了", UrlConfig.LOGIN);
			e.printStackTrace();
		} catch (ExcessiveAttemptsException e) {
			setLoginErrorNumber();
			forwardAction("尝试次数过多 请明天再试", UrlConfig.LOGIN);
		} catch (AuthenticationException e) {
			setLoginErrorNumber();
			forwardAction("对不起 没有权限 访问", UrlConfig.LOGIN);

		} catch (Exception e) {
			setLoginErrorNumber();
			e.printStackTrace();
			forwardAction("请重新登录", UrlConfig.LOGIN);
		}
	}

	private void setLoginErrorNumber() {
		Integer num = 0;
		Object numObj = getSessionAttr(LOGIN_ERROR_NUM);
		if (numObj == null) {
			num = 1;
		} else {
			num = ((Integer) numObj) + 1;
		}
		setSessionAttr(LOGIN_ERROR_NUM, num);
	}

	public void forwardAction(String msg, String url) {
		log.error(msg);
		setAttr("msg", msg);
		forwardAction(url);
	}

	public void unauthorized() {
		render(UrlConfig.VIEW_ERROR_401);
	}

	private void createImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		/*
		 * 得到参数高，宽，都为数字时，则使用设置高宽，否则使用默认值
		 */
		String width = request.getParameter("width");
		String height = request.getParameter("height");
		if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
			w = NumberUtils.toInt(width);
			h = NumberUtils.toInt(height);
		}

		BufferedImage image = new BufferedImage(w, h,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();

		/*
		 * 生成背景
		 */
		createBackground(g);

		/*
		 * 生成字符
		 */
		String s = createCharacter(g);
		request.getSession().setAttribute(VALIDATE_CODE, s);

		g.dispose();
		OutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		out.close();

	}

	private Color getRandColor(int fc, int bc) {
		int f = fc;
		int b = bc;
		Random random = new Random();
		if (f > 255) {
			f = 255;
		}
		if (b > 255) {
			b = 255;
		}
		return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f),
				f + random.nextInt(b - f));
	}

	private void createBackground(Graphics g) {
		// 填充背景
		g.setColor(getRandColor(220, 250));
		g.fillRect(0, 0, w, h);
		// 加入干扰线条
		for (int i = 0; i < 8; i++) {
			g.setColor(getRandColor(40, 150));
			Random random = new Random();
			int x = random.nextInt(w);
			int y = random.nextInt(h);
			int x1 = random.nextInt(w);
			int y1 = random.nextInt(h);
			g.drawLine(x, y, x1, y1);
		}
	}

	private String createCharacter(Graphics g) {
		char[] codeSeq = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
				'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
				'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
		String[] fontTypes = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53",
				"\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
		Random random = new Random();
		StringBuilder s = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);// random.nextInt(10));
			g.setColor(new Color(50 + random.nextInt(100), 50 + random
					.nextInt(100), 50 + random.nextInt(100)));
			g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],
					Font.BOLD, 26));
			g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
			// g.drawString(r, i*w/4, h-5);
			s.append(r);
		}
		return s.toString();
	}

	/**
	 * 测试在 maven 下的 jstl 输出功能 1：确保 web.xml 内容的 app-app 标记中的servlet版本号至少为
	 * 2.5，内容如下： <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 * xmlns="http://java.sun.com/xml/ns/javaee"
	 * xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	 * xsi:schemaLocation=
	 * "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	 * id="WebApp_ID" version="2.5"> 2：确保 jsp 页面中引用了 jstl 标记库，内容如下： <%@ taglib
	 * uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3：确保 jetty
	 * 下开发时引入了正确的依赖，详情在 pom.xml 中有注释说明
	 */
	public void jstl_test() {
		setAttr("blogList", Blog.me.find("select * from blog"));
		renderJsp("/jstl_test.jsp");
	}
}
